package com.biao.synchronized_test;

public class Test02_synchronized implements Runnable {
    private static int count = 100;
    private Object object = new Object();

    @Override
    public void run() {
        while (true) {
            if (count > 1) {
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

//                // 给共享资源添加 synchronized
//                synchronized (this) {
                // 如果new多个对象实例，那每个this都是自己单独的对象，就会出现问题
                // 所以可以锁住 Object
                synchronized (object) {
                    count--;
                    System.out.println(Thread.currentThread().getName() + "---" + count);
                }
            }
        }
    }

    public static void main(String[] args) {
        Test02_synchronized test02Synchronized = new Test02_synchronized();
        // 让两个线程同时执行，去抢同一个资源变量
        new Thread(test02Synchronized).start();
        new Thread(test02Synchronized).start();

    }
}
